package com.atguigu.spzx.common.log.aspect;

import com.atguigu.spzx.common.log.annotation.Log;
import com.atguigu.spzx.common.log.service.AsyncOperLogService;
import com.atguigu.spzx.common.log.utils.LogUtil;
import com.atguigu.spzx.model.entity.system.SysOperLog;
import jakarta.annotation.Resource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * ClassName: LogAspect
 * Package:
 * Description:
 *
 * @Author:xiaohei
 * @Create 2024/5/21 20:59
 * Version 1.0
 */
@Aspect
@Component
public class LogAspect {

    @Resource
    private AsyncOperLogService asyncOperLogService;

    //环绕通知
    @Around(value = "@annotation(sysLog)")
    public Object doAroundAdvice(ProceedingJoinPoint joinPoint, Log sysLog){
//
//        String title = sysLog.title();
//        int i = sysLog.businessType();
//        System.out.println("title" + title);
//        System.out.println("businessType:" + i);

        //业务方法调用之前 封装数据
        SysOperLog sysOperLog = new SysOperLog();
        LogUtil.beforeHandleLog(sysLog,joinPoint,sysOperLog);

        //业务方法
        Object proceed = null;
        try {
            proceed = joinPoint.proceed();
//            System.out.println("业务方法之后执行....");
            //调用业务方法之后实现
            LogUtil.afterHandlLog(sysLog,proceed,sysOperLog,0,null);
        } catch (Throwable e) {
            e.printStackTrace();
            LogUtil.afterHandlLog(sysLog,proceed,sysOperLog,1,e.getMessage());
            throw new RuntimeException();
        }

        //调用service中的方法添加到数据库中去
        asyncOperLogService.saveSysOperLog(sysOperLog);

        return proceed;
    }

}
